<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 * 拼团订单
 */
class Spell extends Api
{
    /**
     * 我的拼团
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="status", type="string", required=true, description="状态012")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     * @ApiParams(name="ptid", type="string", required=true, description="搜索拼团ID")
     */
    public function spellList()
    {
        $model = new \app\admin\model\spell\Spell();
        $status = $this->request->request("status",0);
        $condition = "";
        if($status == 1){
            $condition .= " AND a.isFinished=0";
        }elseif($status == 2){
            $condition .= " AND a.isFinished=1";
        }
        $ptid = $this->request->request("ptid",0);
        if(!empty($ptid)){
            $condition .= " AND a.ptid=".$ptid;
        }
        $sql = "SELECT a.id,a.ptid,a.isFinished,a.totalPrice,a.price,a.balance,b.orderStatus,b.goodsId,a.orderId FROM `pt_spell` as a join `pt_spell_order` as b on a.orderId=b.orderId WHERE a.uid='{$this->auth->id}' AND a.start=1 AND b.orderStatus in(2,3,4,5,6,7,9) $condition ORDER BY a.id desc LIMIT ". ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $goods = \app\admin\model\goods\Goods::where('goodsid', $vs['goodsId'])->field('indexCategory')->find();
                $vs['indexCategory'] = $goods['indexCategory'];
                $spellList = $model->where('ptid',$vs['ptid'])->order('id asc')->field('mobile,avatar,price,start,robot,price,orderId')->select();
                $vs['spellList'] = !empty($spellList)?$spellList:[];
                $goodsInfo = \app\admin\model\SpellOrder::where('id',$vs['ptid'])->field('id,goodsName,thumb,goodsPrice')->find();
                $vs['goodsInfo'] = !empty($goodsInfo)?$goodsInfo:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
            "finishInfo"=>$model::getFinishInfo(),
        );
        $this->success("我的拼团订单",$data);
    }
    /**
     * 我的订单
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="status", type="string", required=true, description="状态012345")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function orderList()
    {
        $model = new \app\admin\model\SpellOrder();
        $query = $model->where('uid',$this->auth->id);
        $status = $this->request->request("status",0);
        if($status == 1){
            $query->where("orderStatus",1);
        }elseif($status == 2){
            $query->where("orderStatus",2)->where('model',2);
        }elseif($status == 3){
            $query->where("orderStatus",3);
        }elseif($status == 4){
            $query->where("orderStatus",'in',[4,5]);
        }elseif($status == 5){
            $query->where("orderStatus",'in',[6,7]);
        }
        $ptid = $this->request->request("ptid",0);
        if(!empty($ptid)){
            $query->where("id",$ptid);
        }
//        $query->where('model','in',[1,2]);
        $list = $query->limit(($this->page-1)*$this->limit,$this->limit)
            ->field('id,uid,model,goodsName,skuName,thumb,goodsPrice,goodsNum,goodsId,payPrice,orderStatus,orderId,payType')
            ->order('id desc')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->select();
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $goods = \app\admin\model\goods\Goods::where('goodsid', $vs['goodsId'])->field('indexCategory')->find();
                $vs['indexCategory'] = $goods['indexCategory'];
                $spellList = [];
                if($vs['model'] == 2){
                    $spellList = \app\admin\model\spell\Spell::where('ptid',$vs['id'])->order('id asc')->field('totalPrice,price,balance,mobile,avatar,price,start,robot,orderId')->select();
                }
                $vs['spellList'] = $spellList;
            }
        }
        $model::crontab($this->auth->id);
        $data = array(
            "list"=>!empty($list)?$list:[],
            "orderStatus"=>[
                1=>$model->orderStatusInfo(1),
                2=>$model->orderStatusInfo(2),
                3=>$model->orderStatusInfo(3),
            ],
            "backPercent"=>bcadd(100, \think\config::get("site.pingorderbackpercent")),
        );
        $this->success("我的订单",$data);
    }
    /**
     * 取消订单
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function cancelOrder()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->find();
        if(empty($orderInfo) || !@in_array($orderInfo->orderStatus,[1,2])){
            $this->error("订单信息获取失败");
        }
        Db::startTrans();
        if($orderInfo->orderStatus == 1){
            $orderInfo->save(['orderStatus'=>10]);
        }elseif($orderInfo->orderStatus ==2){     //已支付退款
            try{
                $return = \app\admin\model\spell\Refund::getReturnAmount($orderInfo)[0];
                if($return <= 0){
                    throw new Exception("时间未到，无法取消");
                }

                $re = $model->where('id',$orderInfo['id'])->where('orderStatus',2)->update(['orderStatus'=>10,'canceltime'=>time()]);
                if($re == false){
                    throw new Exception("操作失败");
                }
                \app\admin\model\spell\Refund::returnOrder($orderInfo,$return);
            }catch (\Exception $e){
                Db::rollback();
                $this->error("退款失败:".$e->getMessage());
            }
        }
        Db::commit();
        $this->success("取消成功");
    }
    /**
     * 订单回购
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function orderBuyBack()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus',3)->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        Db::startTrans();
        try{
            $re = $model->where('id',$orderInfo['id'])->where('orderStatus',3)->update(['orderStatus'=>7,'backtime'=>time()]);
            if($re == false){
                throw new Exception("操作失败");
            }
            \app\admin\model\spell\Back::buyBackInfo($orderInfo);
        }catch (\Exception $e){
            Db::rollback();
            $this->error("回购失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("回购成功");
    }
    /**
     * 订单确认发货
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function agreeDelivery()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus','in',[3,11])->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        Db::startTrans();
        try{
            $orderInfo->save(['orderStatus'=>4,'updatetime'=>time()]);
            if($orderInfo['model']==3){
                \app\common\library\Sms::otherSend([
                    "uid"=>$orderInfo['uid'],
                    "type"=>11,
                ]);
            }
        }catch (\Exception $e){
            Db::rollback();
            $this->error("确认发货失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("确认发货成功");
    }
    /**
     * 订单确认收货
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function confirmOrder()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus',5)->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        Db::startTrans();
        try{
            $orderInfo->save(['orderStatus'=>6,'finishtime'=>time()]);
        }catch (\Exception $e){
            Db::rollback();
            $this->error("确认收货失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("确认收货成功");
    }
    /**
     * 物流信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function logisticsInfo()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus',"in",[5,6,9])
            ->field('id,orderId,model,goodsName,thumb,goodsPrice,expressNo,expressName,orderStatus,createtime,payTime,delivertime')->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        $logList = [
            [
                "time"=>date("Y-m-d H:i:s",$orderInfo['delivertime']),
                "context"=>"订单已进入商家仓库，正在打包中",
                "status"=>"备货中",
                "day"=>date("m-d",$orderInfo['delivertime']),
                "times"=>date("H:i",$orderInfo['delivertime']),
            ],
            [
                "time"=>date("Y-m-d H:i:s",$orderInfo['payTime']),
                "context"=>"订单支付成功，系统正在处理",
                "status"=>"已下单",
                "day"=>date("m-d",$orderInfo['payTime']),
                "times"=>date("H:i",$orderInfo['payTime']),
            ],
            [
                "time"=>date("Y-m-d H:i:s",$orderInfo['createtime']),
                "context"=>"订单创建成功，等待支付",
                "status"=>"已创建",
                "day"=>date("m-d",$orderInfo['createtime']),
                "times"=>date("H:i",$orderInfo['createtime']),
            ],
        ];
        $info = $model->getExpressList($orderInfo);
        if(!empty($info)){
            foreach ($info as $ks=>$vs){
                $info[$ks]['day'] = "";
                $info[$ks]['times'] = "";
                if(!empty($vs['time'])){
                    $time = strtotime($vs['time']);
                    $info[$ks]['day'] = date("m-d",$time);
                    $info[$ks]['times'] = date("H:i",$time);
                }
            }
            $logList = array_merge($info,$logList);
        }
        $data = [
            'list' => $info?$logList:[],
            "orderInfo"=>$orderInfo,
            'url' => empty($info)?"https://m.kuaidi100.com/result.jsp?nu=" . $orderInfo['expressNo']:"",
        ];
        $this->success("物流信息返回",$data);
    }
    /**
     * 评论
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     * @ApiParams(name="goods", type="string", required=true, description="商品描述")
     * @ApiParams(name="info", type="string", required=true, description="评论")
     * @ApiParams(name="thumbs", type="string", required=true, description="图片")
     * @ApiParams(name="express", type="string", required=true, description="物流服务")
     * @ApiParams(name="service", type="string", required=true, description="服务态度")
     */
    public function commentOrder()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus','in',[6,7])->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        Db::startTrans();
        try{
            $re = $model->where('id',$orderInfo['id'])->where('orderStatus','in',[6,7])->update(['orderStatus'=>9,'backtime'=>time()]);
            if($re == false){
                throw new Exception("操作失败");
            }
            \app\admin\model\spell\Comment::addInfo($orderInfo,$this->request->request());
        }catch (\Exception $e){
            Db::rollback();
            $this->error("评论失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("评论成功");
    }
    /**
     * 订单商品
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function goodsList()
    {
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $sql = "SELECT id,goodsName,skuName,image,price,returnStatus FROM `pt_spell_detail` WHERE uid='{$this->auth->id}' AND orderId='{$orderId}' ORDER BY id asc";
        $list = Db::query($sql);
        $data =array(
            "list"=>!empty($list)?$list:[],
            "returnStatus"=>\app\admin\model\SpellOrder::returnStatusInfo(),
        );
        $this->success("订单商品数据",$data);
    }
    /**
     * 退货订单申请
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     * @ApiParams(name="detailId", type="string", required=true, description="商品记录ID")
     * @ApiParams(name="applyModel", type="string", required=true, description="申请类型")
     * @ApiParams(name="orderStatus", type="string", required=true, description="商品状态")
     * @ApiParams(name="applyInfo", type="string", required=true, description="退款原因")
     * @ApiParams(name="info", type="string", required=true, description="退款说明")
     * @ApiParams(name="thumbs", type="string", required=true, description="图")
     * @ApiParams(name="mobile", type="string", required=true, description="联系方式")
     * @ApiParams(name="price", type="string", required=true, description="退款金额")
     */
    public function returnOrder()
    {
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = \app\admin\model\SpellOrder::where('uid',$this->auth->id)->where('orderId',$orderId)->where('orderStatus','in',[4,5,6])->find();
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        $detailId = $this->request->request("detailId",0);
        if(empty($detailId)){
            $this->error("商品信息获取失败");
        }
        $detail = Db::query("SELECT * FROM `pt_spell_detail` WHERE orderId='{$orderId}' AND id='{$detailId}' AND returnStatus=0");
        if(empty($detail)){
            $this->error("商品信息获取失败");
        }
        $goodsInfo = $detail[0];
        if($goodsInfo["returnStatus"] != 0){
            $this->error("退货已申请");
        }
        Db::startTrans();
        try{
            Db::query("UPDATE `pt_spell_detail` SET returnStatus=1,updatetime=".time()." WHERE id='{$goodsInfo['id']}' AND returnStatus=0");
            \app\admin\model\spell\Returned::addInfo($orderInfo,$goodsInfo,$this->request->request());
        }catch (\Exception $e){
            Db::rollback();
            $this->error("申请失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("退款申请成功,请耐心等待审核!");
    }
    /**
     * 退款订单列表
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="status", type="string", required=true, description="状态01")
     * @ApiParams(name="page", type="string", required=true, description="分页")
     */
    public function returnList()
    {
        $model = new \app\admin\model\spell\Returned();
        $query = $model->where('uid',$this->auth->id)->where('status','<>',10);
        $status = $this->request->request("status",0);
        if($status == 1){
            $query->where('status',3);
        }
        $list = $query->order('id desc')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->field('id,goodsName,skuName,thumb,goodsNum,goodsPrice,returnPrice,status,orderId,createtime,applyModel,orderStatus,applyInfo')
            ->select();
        $data = array(
            "list"=>!empty($list)?$list:[],
            "statusInfo"=>$model->statusInfo(),
            "applyModel"=>$model->applyModel(),
            "orderStatus"=>$model->orderStatus(),
            "expressList"=>$model->expressList(),
        );
        $this->success("售后订单",$data);
    }
    /**
     * 补全物流信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="returnId", type="string", required=true, description="退款ID")
     * @ApiParams(name="expressName", type="string", required=true, description="快递公司")
     * @ApiParams(name="expressNo", type="string", required=true, description="快递单号")
     */
    public function expressReturn()
    {
        $model = new \app\admin\model\spell\Returned();
        $returnId = $this->request->request("returnId",0);
        if(empty($returnId)){
            $this->error("订单获取失败");
        }
        $returnInfo = $model->where('id',$returnId)->where('uid',$this->auth->id)->where('status',3)->find();
        if(empty($returnInfo)){
            $this->error("订单获取失败");
        }
        Db::startTrans();
        try{
            \app\admin\model\spell\Returned::expressInfo($returnInfo,$this->request->request());
        }catch (\Exception $e){
            Db::rollback();
            $this->error("补全失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("补全信息成功");
    }
    /**
     * 撤销退款申请
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="returnId", type="string", required=true, description="退款ID")
     */
    public function cancelReturn()
    {
        $model = new \app\admin\model\spell\Returned();
        $returnId = $this->request->request("returnId",0);
        if(empty($returnId)){
            $this->error("订单获取失败");
        }
        $returnInfo = $model->where('id',$returnId)->where('uid',$this->auth->id)->where('status','in',[1,3,4])->find();
        if(empty($returnInfo)){
            $this->error("订单获取失败");
        }
        Db::startTrans();
        try{
            \app\admin\model\spell\Returned::cancelInfo($returnInfo);
        }catch (\Exception $e){
            Db::rollback();
            $this->error("申请失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("撤销退款申请成功");
    }
    /**
     * 删除退款申请
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="returnId", type="string", required=true, description="退款ID")
     */
    public function deleteReturn()
    {
        $model = new \app\admin\model\spell\Returned();
        $returnId = $this->request->request("returnId",0);
        if(empty($returnId)){
            $this->error("订单获取失败");
        }
        $returnInfo = $model->where('id',$returnId)->where('uid',$this->auth->id)->where('status',9)->find();
        if(empty($returnInfo)){
            $this->error("订单获取失败");
        }
        Db::startTrans();
        try{
            \app\admin\model\spell\Returned::deleteInfo($returnInfo);
        }catch (\Exception $e){
            Db::rollback();
            $this->error("删除失败:".$e->getMessage());
        }
        Db::commit();
        $this->success("删除退款申请成功");
    }
    /**
     * 拼团消息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function spellMessage()
    {
        $model = new \app\admin\model\spell\Spell();
        $list = $model->limit(10)->field('mobile,price,createtime')->order('id desc')->select();
        $data = array(
            "list"=>!empty($list)?$list:[]
        );
        $this->success("拼团消息",$data);
    }
    /**
     * 订单取消信息
     */
    public function cancelInfo()
    {
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单信息获取失败");
        }
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->find();
        if(empty($orderInfo) || !@in_array($orderInfo->orderStatus,[1,2])){
            $this->error("订单信息获取失败2");
        }
        $return = 100;
        if($orderInfo->orderStatus ==2){//已支付退款
            try{
                $return = \app\admin\model\spell\Refund::cancelInfo($orderInfo);
                $countPrice = \app\admin\model\spell\Spell::where('ptid',$orderInfo['id'])->where('start',0)->where('robot',0)->sum("price");
                if($countPrice>=$orderInfo['payPrice']){
                    $return=100;
                }else{
                    $return=70;
                }
            }catch (\Exception $e){
                $this->error("取消失败:".$e->getMessage());
            }
        }
        $day = \think\config::get("site.pingorderreturnday");
        $this->success("返回取消比例",['return'=>$return,'day'=>$day]);
    }
}
